package com.example.aigc_education.integration.processor.v2;

import com.alibaba.fastjson.JSONObject;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.integration.config.RestTemplateUtils;
import com.example.aigc_education.integration.impl.CozeTokenIntegrationImpI;
import com.example.aigc_education.integration.request.CozeRequest;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Coze工作流处理器基类
 * 提供所有处理器共用的基础功能
 * @param <T> 请求参数类型
 */
public abstract class BaseCozeProcessor<T> {
    @Resource
    protected CozeTokenIntegrationImpI cozeTokenIntegration;

    private static final String COZE_WORKFLOW_URL = "/workflow/run";

    /**
     * 获取工作流ID
     * @return 工作流ID
     */
    protected abstract String workflowId();

    /**
     * 参数校验
     * @param request 请求参数
     * @return 校验结果
     */
    protected abstract boolean isParamValid(CozeRequest<T> request);

    /**
     * 构建HTTP请求头
     * @return HTTP请求头
     */
    protected Map<String, String> buildHeaders() {
        Map<String, String> headerMap = new HashMap<>();
        String cozeToken = cozeTokenIntegration.getCozeToken();
        headerMap.put("Authorization", String.format("Bearer %s", cozeToken));
        headerMap.put("Content-Type", "application/json");
        return headerMap;
    }

    /**
     * 执行HTTP请求
     * @param url 请求URL
     * @param jsonObject 请求参数
     * @return 响应结果
     */
    protected String executeHttpRequest(String url, JSONObject jsonObject) {
        return Optional.ofNullable(RestTemplateUtils.postHttp(url, jsonObject, buildHeaders()))
                .orElseThrow(() -> new BusinessException("请求Coze服务失败"));
    }
}
